package com.elsewhat.reddittv.hd;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.elsewhat.reddittv.hd.api.RedditPost;
import com.elsewhat.reddittv.hd.fragments.MyPreferenceFragment;
import com.elsewhat.reddittv.hd.fragments.RedditPostListFragment;
import com.elsewhat.reddittv.hd.fragments.SubredditListFragment;
import com.elsewhat.reddittv.hd.fragments.WelcomeFragement;
import com.elsewhat.reddittv.hd.fragments.YoutubePlayerFragement;
import com.elsewhat.reddittv.hd.fragments.RedditPostListFragment.OnRedditPostSelectedListener;
import com.elsewhat.reddittv.hd.fragments.SubredditListFragment.OnSubredditSelectedListener;
import com.elsewhat.reddittv.hd.fragments.YoutubePlayerFragement.YoutubePlayerEventsListener;

public class RedditTVHDActivity extends Activity implements OnSubredditSelectedListener, TabListener,OnSharedPreferenceChangeListener, OnRedditPostSelectedListener, YoutubePlayerEventsListener {
	ActionBar actionBar;
	public static final String LOG_PREFIX = "RedditTV HD";
	public static final String PREFS_NAME = "RedditTVHDPreferences";
	
	protected ArrayList<RedditPost> playlist;
	protected ArrayList<RedditPost> playlistCompleted;
	protected RedditPost nowPlayingPost;
	
	//required for dynamically updating the text
	protected Tab playlistTab;
	

	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (savedInstanceState != null) {

		}

		/* Stop ListenToThis if notification has been clicked on
		Intent incomingIntent =getIntent();
		if(incomingIntent!=null){
			//TODO check for value if several actions exist
			if(incomingIntent.getAction()!=null && incomingIntent.getAction().equalsIgnoreCase(INTENT_STOP_LISTENTO) ){
				try {
					if(mediaplayer!=null && mediaplayer.isPlaying()){
						notifyUser("Stopping audio playback");
						mediaplayer.stop();
						mediaplayer.release();
					}
				}catch (IllegalStateException e) {
					//ignore
				}

			}
		}*/
		if (getIntent()!=null && getIntent().getData()!=null){
			//doDisplayUserMsg("Received incoming url "+ getIntent().getData() + ". \nHandling of event not implemented yet" );
			//TODO: Implement handling of incoming url
		}

		playlist = new ArrayList<RedditPost>(20);
		playlistCompleted= new ArrayList<RedditPost>(20);
		
		setContentView(R.layout.main);
		actionBar=getActionBar();
		actionBar.setSubtitle(R.string.actionbar_subtitle);
		
	    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	    // remove the activity title to make space for tabs
	    actionBar.setDisplayShowTitleEnabled(false);

	    // add a new tab and set its title text and tab listener
	    actionBar.addTab(actionBar.newTab().setText(R.string.tab_reddits_title).setTabListener(this));
	    playlistTab = actionBar.newTab().setText(R.string.tab_playlist_title).setTabListener(this);
	    updatePlaylistTabText();
	    actionBar.addTab(playlistTab);
	    

		// set default fragements
		FragmentManager fragmentManager = getFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.addToBackStack(null);

		// TODO: Use setArguments instead?
		SubredditListFragment redditListFragment = new SubredditListFragment(this);
		fragmentTransaction.add(R.id.frag_list, redditListFragment,
				"RedditListFragment");

		WelcomeFragement welcomeFragement = new WelcomeFragement();
		fragmentTransaction.add(R.id.frag_main, welcomeFragement,
				"WelcomeFragment");

		fragmentTransaction.commit();
	}
	
	public void updatePlaylistTabText(){
		//setting the text of existing tab doesn't redraw the text, so let's readd it
		if(getActionBar().getTabCount()==2){
			CharSequence title = getResources().getText(R.string.tab_playlist_title);
			playlistTab = actionBar.newTab().setText(title + " ("+playlist.size()+")").setTabListener(this);
			getActionBar().removeTabAt(1);
			getActionBar().addTab(playlistTab);	
		}
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater infalter = getMenuInflater();
		infalter.inflate(R.menu.main_menu, menu);
		// Get the SearchView and set the searchable configuration
		/*SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu
				.findItem(R.id.menu_search).getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));
		searchView.setIconifiedByDefault(true); // Do not iconify the
													// widget; expand it by
													// default
													
		 */

		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {

	
		switch (item.getItemId()) {
		case R.id.menu_preferences:
			actionDisplayPreferences();
			return true;
        case android.R.id.home:
            // app icon in Action Bar clicked; go home
            Intent homeIntent = new Intent(this, RedditTVHDActivity.class);
            homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(homeIntent);
            return true;
		default:
			//handle fragment bug
			//http://stackoverflow.com/questions/5297842/how-to-handle-oncontextitemselected-in-a-multi-fragment-activity
			//my fragment's onContextItemSelected is not called at all
			FragmentManager fragmentManager = getFragmentManager();
			Fragment fragmentInList= fragmentManager.findFragmentById(R.id.frag_list);
			if(fragmentInList!=null){
				return fragmentInList.onContextItemSelected(item);
			}else {
				
				notifyUser("Could not handle action for menu item with id "
						+ item.getItemId());
			}


		}

		// TODO handle non-link actionbar items
		// TODO Auto-generated method stub
		return super.onMenuItemSelected(featureId, item);

	}



	public void actionDisplayPreferences() {
		FragmentManager fragmentManager = getFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.addToBackStack(null);

		// supply link to constructor
		MyPreferenceFragment newFragment = new MyPreferenceFragment();
		fragmentTransaction.replace(R.id.frag_main, newFragment,
				"MyPreferenceFragment");
		fragmentTransaction
				.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		fragmentTransaction.commit();
	}

	private void notifyUser(CharSequence msg) {
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}
	
	private void notifyUser(int resourceId) {
		Toast.makeText(this, resourceId, Toast.LENGTH_LONG).show();
	}
	
	@Override
	public void onSubredditSelected(String subreddit) {
		FragmentManager fragmentManager = getFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.addToBackStack(null);

		// supply link to constructor
		RedditPostListFragment newFragment = new RedditPostListFragment(this,subreddit);
		fragmentTransaction.replace(R.id.frag_list, newFragment,
				"RedditPostListFragment");
		fragmentTransaction
				.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		fragmentTransaction.commit();
		
		//notifyUser("Subreddit " + subreddit + " selected");
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		/*
		if(key!=null&& key==RedditTVPreferences.KEY_REDDIT_USERNAME){
			if(redditAPI.isLoggedIn(this)){
				notifyUser("Logging you out as reddit user has changed");
			}
			redditAPI.doDeleteLocalLoginInformation(this);
		}
		if(key!=null&& key==RedditTVPreferences.KEY_REDDIT_LOGOUT){
			if(redditAPI.isLoggedIn(this)){
				notifyUser("Forced logout from reddit");
				RedditTVPreferences.deleteStoredRedditSessionCookie(this);
				redditAPI.doDeleteLocalLoginInformation(this);
			}else {
				notifyUser("No forced logout as you are not logged in");
			}
			String value = sharedPreferences.getString(key,null);
		}
		*/
		
		
	}

	@Override
	public void watch(RedditPost redditPost) {
		FragmentManager fragmentManager = getFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		//fragmentTransaction.addToBackStack(null);

		// supply link to constructor
		YoutubePlayerFragement newFragment = new YoutubePlayerFragement(this,redditPost);
		fragmentTransaction.replace(R.id.frag_main, newFragment,
				"YoutubePlayerFragement");
		fragmentTransaction
				.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		fragmentTransaction.commit();
	}

	@Override
	public RedditPost videoFinished(RedditPost redditPost) {
		Log.i(RedditTVHDActivity.LOG_PREFIX, "Finished playing "+redditPost);
		playlistCompleted.add(0,redditPost);
		
		if(playlist.size()==0){
			notifyUser(R.string.msgPlaylistEmpty);
			return null;
		}else {
			nowPlayingPost = playlist.remove(0);
			CharSequence msgNowPlaying = getResources().getText(R.string.msgNowPlaying);
			notifyUser(msgNowPlaying+"\n"+nowPlayingPost.getTitle());
			updatePlaylistTabText();
			return nowPlayingPost;
		}
	}

	@Override
	public void queue(RedditPost redditPost) {
		playlist.add(redditPost);
		updatePlaylistTabText();
	}

	@Override
	public void queueAsNext(RedditPost redditPost) {
		playlist.add(0,redditPost);
		updatePlaylistTabText();
	}

}
